***Set paths
local dir "..."
local dropbox_data "..."
local dropbox_data_create "..."
local local_data "..."
local dropbox_fig "..."
local dropbox_tab "..."

local F=100
clear 
clear matrix
clear mata 
set maxvar 120000 


************************************************************
*** MARKET FEATURES USED IN THE TEXT OF THE DRAFT 
	*Using full data (w/o restrictions for structural estimation)
************************************************************

*** KEY MARKET FEATURES PARAGRAPH
use "`local_data'/data_base_bonds_bills.dta", clear 
keep if market_type=="secondary" &  counter_type=="CLIENT"
drop if gleif_related=="Y"

*How many dealer IDs?
unique bidderid if market_type=="secondary"

*How many investor IDs?
egen lei= group(LEI)
egen lei_max = max(lei)
bys LEI: gen ids = _n if LEI=="anonymous"	
replace lei = lei_max+ids  if LEI=="anonymous"	
unique lei 

*Days since last auction (per isin)
preserve
use "`local_data'/data_base_bonds_bills.dta", clear 
keep if (market_type=="auction" & (auctiontype=="TBREG" | auctiontype=="BDREG" | auctiontype=="CM" | auctiontype=="NF") ) 
gen last_auction=AuctionDate  if auctiontype=="TBREG" | auctiontype=="BDREG" | auctiontype=="CM" | auctiontype=="NF"
tempfile temp
save  `temp' , replace
restore
append using `temp'

format last_auction %td
sort  isin date  market_type
bys isin (date market_type): replace last_auction = last_auction[_n-1] if last_auction >= . 
gen days_post_auction = date - last_auction
keep if market_type=="secondary"
tabstat days_post_auction, stats(min max p50 mean sd)
	*---> about 90 days since auction in the median (per isin)

*Days to maturity of bonds
gen years_to_maturity = days_to_maturity_e/365
tabstat years_to_maturity , stats(min max p50 mean sd)
	*---> Median trade is with a bond that has less than 4.5 years left to maturity

*Time between transactions 
bys date  (exec_time): gen time_diff = (exec_time - exec_time[_n-1])/(1000*60) //in minutes
bys date isin_id (exec_time): gen time_diff_isin = (exec_time - exec_time[_n-1])/(1000*60) //in minutes
tabstat time_diff time_diff_isin, stats(count mean p50)
	*--> .11 mins and 2.5 mins per isin

*Bid-ask spread
gen spread= bidyield_can-askyield_can  
tabstat spread, stats(p50)
	*--> median 0.5 bps spread


*** AVERAGE TRADE FOR BPS to VALUE CONVERSION 
*Average trade size
bys retailer: tabstat IIROC_QUANTITY
	*--> avg: .3462309  mio (for retailers)
	*--> avg:  14.89506 mio (for institutional)
	
tabstat IIROC_QUANTITY IIROC_YIELD
bys retailer: tabstat IIROC_YIELD 
	*---> 1 bps is how much in gains of trade
		  *(IIROC_YIELD/100^2 * avg.size)/100
		 
*Amount traded in a year of investors with LEIs
preserve
gen month=month(date)
collapse (sum) IIROC_QUANTITY, by(lei year month retailer trackclient)
tabstat IIROC_QUANTITY if retailer==0 , stats(min max p50 mean sd) 
	*-- 35.73362 per month for the average institutional investor
restore 

		  	
*** TRADE VOLUMNE FOR HOW MUCH DO DEALERS LOOSE CALCULATION FOR DEALERS WE FOCUS ON 
preserve
gen bigdealers = ( bidderid==18 | bidderid==24 | bidderid==46 | bidderid==61 | bidderid==67|bidderid==77 | bidderid==83 | bidderid==88 | bidderid==93 | bidderid==94 | bidderid==18001 | bidderid==24001 | bidderid==46001)
replace bidderid=46 if bidderid==46001
replace bidderid=24 if bidderid==24001
replace bidderid=18 if bidderid==18001

*large trade indicator 
gen large_trade = (IIROC_QUANTITY>=25)
collapse (sum) IIROC_QUANTITY, by(bidderid bigdealers year large_trade)
tabstat IIROC_QUANTITY if bigdealers==1 & large_trade==0, stats(min max p50 mean sd)
	*---103097.3 million per year 
restore 


*** AVERAGE MONTHLY TRADE AMOUNT ON CANDEAL 
preserve
keep if trading_venue=="CanDeal"
gen month=month(date)
collapse (sum) IIROC_QUANTITY, by(month year lei )
tabstat IIROC_QUANTITY , stats(mean p50 min max sd)
	*--a typical institutional investor trades 22 million on the platform per month (mean is 22.4353)
restore
  

*** WELFARE TABLE TRADE VOLUME 
gen large_trade = (IIROC_QUANTITY>=25)
collapse (sum) IIROC_QUANTITY, by( year large_trade)
tabstat IIROC_QUANTITY if large_trade==0, stats(min max p50 mean sd)
	*--1,072,198
	*Welfare gain in bps/9 (because we have 9 dealers) * 1/100^2 * 1072198. 
	*For 62 bps we get: 738.63e+06, For 37 bps we get: 440.7925 million


************************************************************
*** FIGURES using data s.t. restrictions used in structural estimation 
************************************************************

****************
*** FIGURE 1a
****************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

keep if bidderid==18 | bidderid==24 | bidderid==46 | bidderid==61 | bidderid==67|bidderid==77 | bidderid==83 | bidderid==88 | bidderid==93 | bidderid==94 | bidderid==18001 | bidderid==24001 |bidderid==46001
replace bidderid=18 if bidderid==18001
replace bidderid=24 if bidderid==24001
replace bidderid=46 if bidderid==46001

foreach i in 3 4 {
preserve

if (`i'==2){ // curently not used
	*conditional on trading more than 10 times 
	bys LEI: gen N_trades = _N
	gen quarter = quarter(date)
	bys year quarter LEI: gen N_trades_m = _N
	bys LEI: egen N_trades_m_min = min(N_trades_m) 
	keep if N_trades_m_min>=10
}

*create indicator for how number of trades 
bys LEI: gen N_trades = _N 

*create indicators for number of trades per trading venue
bys LEI trading_venue: gen a0 = _N if trading_venue=="CanDeal"
bys LEI: egen N_trades_candeal=max(a0) 
replace N_trades_candeal=0 if N_trades_candeal==.
drop a0 
bys LEI trading_venue: gen a0 = _N if trading_venue=="OTC"
bys LEI: egen N_trades_otc=max(a0)
replace N_trades_otc=0 if N_trades_otc==.
drop a0

*cutoff for most frequent traders based on full sample
bys LEI: gen a0=_n 
bys trackclient a0: egen a1= pctile(N_trades) if a0==1, p(75)
bys trackclient: egen N_trades_large_cutoff=max(a1)
tab N_trades_large_cutoff
tab N_trades if trackclient=="market-wide" & a0==1

if (`i'==3){
	*conditional on trading OTC
	keep if trading_venue=="OTC"
}

if (`i'==4){
	*conditional on trading CanDeal
	keep if trading_venue=="CanDeal"
}

collapse IIROC_QUANTITY, by(bidderid LEI trackclient N_trades_candeal N_trades_otc N_trades N_trades_large_cutoff)

bys LEI : gen a1=_n 
bys LEI : gen a0=_N  // number of dealers a LEI has 
keep if a1==1

*all investors  
gen freq1 =1
*conditional on being a LEI investor
gen freq2 =(trackclient=="market-wide")
*conditional on trading 10 times and being LEI 
gen freq4 =  (N_trades>=10  & trackclient=="market-wide")
*conditional on trading 10 times on CanDeal and OTC
gen freq3 =  (N_trades_candeal>=10 & N_trades_otc>=10 &  N_trades_candeal!=. & N_trades_otc!=. & trackclient=="market-wide")
*conditional on trading 10 times on CanDeal 
gen freq5 =  (N_trades_candeal>=10 & N_trades_candeal!=. & trackclient=="market-wide")
*conditional on being a frequent LEI trader  
gen freq6 =  (N_trades>=N_trades_large_cutoff & N_trades!=. & trackclient=="market-wide")

collapse (sum) freq1 freq2 freq3 freq4 freq5 freq6, by(a0) // count the investors who have 1., ... 10 dealers (this number is in a0)
 
egen tot1=total(freq1)
gen share1 = freq1/tot1*100 

egen tot2=total(freq2)
gen share2 = freq2/tot2*100 

egen tot3=total(freq3)
gen share3 = freq3/tot3*100 

egen tot4=total(freq4)
gen share4 = freq4/tot4*100 

egen tot5=total(freq5)
gen share5 = freq5/tot5*100 

egen tot6=total(freq6)
gen share6 = freq6/tot6*100 

collapse share1 share2 share3 share4 share5 share6, by(a0)

*save to create combined graph 
foreach k of numlist 1/6{
	gen share`k'_`i'=share`k'
}
keep share1_`i' share2_`i'  share3_`i'  share4_`i'  share5_`i'   share6_`i' a0
tempfile temp_`i'
save  `temp_`i'' , replace

restore 
}

*create the graph
use  `temp_3', clear 
append using `temp_4'
graph bar share1_3 share1_4 share2_3 share2_4, over(a0,lab(labsize(large))) yti("% of investors", size(large))  leg(order(1 2 3 4) size(small) label(1 "bilateral (all)") label(2 "platform (all)")  label(3 "bilateral (LEIs)") label(4 "platform (LEIs)")  region(lc(white))) bar(1, fcolor(navy%70) lcolor(black)) bar(2, fcolor(emidblue%40) lcolor(black))  bar(3, fcolor(dkgreen%50) lcolor(black))   bar(4, fcolor(green%10)  lcolor(black))   graphregion(color(white))   legend(size(large)) b1title("number of dealers",size(large))
graph export "`dropbox_fig'/graph_N_dealer_combined.png", replace



****************
*** FIGURE 1b
****************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

keep if bidderid==18 | bidderid==24 | bidderid==46 | bidderid==61 | bidderid==67|bidderid==77 | bidderid==83 | bidderid==88 | bidderid==93 | bidderid==94 | bidderid==18001 | bidderid==24001 |bidderid==46001
replace bidderid=18 if bidderid==18001
replace bidderid=24 if bidderid==24001
replace bidderid=46 if bidderid==46001

*homedealer assignment 
do "Homedealer.do"

*create indicator for low number of trades 
bys LEI: gen N_trades = _N 

*how many of all trades are with the home dealer?
preserve
bys homedealer LEI: gen N_trades_dealer = _N if homedealer==1
bys homedealer LEI: egen Q_trades_dealer =total(IIROC_QUANTITY) if homedealer==1
bys LEI: egen Q_trades = total(IIROC_QUANTITY)
gen share_dealer = N_trades_dealer/N_trades*100
gen share_dealerQ = Q_trades_dealer/Q_trades*100
keep if trackclient=="market-wide" & homedealer==1
collapse share_dealer share_dealerQ, by (LEI)
tabstat share_dealer share_dealerQ
restore

*how often does an investor trade bilaterally with a non-home dealer 
bys LEI trading_venue: gen N_trades_venue=_N
bys homedealer LEI trading_venue: gen N_trades_dealer = _N 
bys homedealer LEI trading_venue: egen Q_trades_dealer =total(IIROC_QUANTITY) 
bys LEI trading_venue: egen Q_trades_venue = total(IIROC_QUANTITY)
gen share_dealer = N_trades_dealer/N_trades_venue*100
gen share_dealerQ = Q_trades_dealer/Q_trades_venue*100
keep if trackclient=="market-wide" 
collapse share_dealer share_dealerQ, by (LEI trading_venue homedealer)
gen trading_venue2 = "bilateral" if trading_venue=="OTC"
replace trading_venue2 = "platform" if trading_venue=="CanDeal"

graph box  share_dealerQ if homedealer==1, over(trading_venue2, lab(labsize(large))) yti("% of trade volume", size(vlarge)) ///
ylabel(,labsize(vlarge))  graphregion(color(white))  ///
marker(1, msize(vsmall) msymbol(circle_hollow) mcolor(black%70))  bar(1, fcolor(white) lcolor(black))  marker(2, msize(vsmall) msymbol(circle_hollow) mcolor(gray%70))  bar(2, fcolor(white) lcolor(gray))   legend(size(large))  medtype(marker) medmarker(mcolor(black%80))  
graph export "`dropbox_fig'/graph_home_dealer_trades_both2.png", replace	
	


****************
*** FIGURE 2a 
****************

*** Load data  (careful includes inhouse)
use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

*variables 
gen retailer_intro=(retailer==1)
label define retailer_intro_lab 0 "institutional (access)" 1 "retail (no access)" 				   
label values retailer_intro retailer_intro_lab  

drop markup markup2 
gen markup   		=  (yield - midyield_bl_norm)
gen markup2 		=   markup if IIROC_SIDE=="BUY" 
replace markup2 	= - markup if IIROC_SIDE=="SELL" 

*control for dealer, security and hour fixed effect
reghdfe markup2 retailer, absorb(bidderid isin_id exec_time_grid)    vce(cluster isin_id)  residuals(resids)

*combine
gen markup_res=.
replace markup_res = resids if retailer==0 
replace markup_res =  _b[retailer] + resids   if retailer==1 

*set bounds for box plot
sort retailer
by retailer: egen p5 = pctile(markup_res), p(5)
by retailer: egen p95 = pctile(markup_res), p(95)

graph box   markup_res if markup_res>p5 & markup_res<p95,  over(retailer_intro,label(labsize(large)))     yti("basis points", size(large)) ylabel(,labsize(large))  yline(0,lpattern(dash) lcolor(black)) leg(order(1 2) row(1)  label(1 "institutional investor", size(large)) label(2 "retail investor", size(large)) region(lc(white))) graphregion(color(white))  marker(1, msize(vsmall) msymbol(circle_hollow) mcolor(black%70))  bar(1, fcolor(white) lcolor(black)) 
graph export "`dropbox_fig'/graph_prices_slides_pretty_bps.png", replace


****************
****** FIGURES 2b and 3 are created in EventStudy.do and Figure3.do, respectively.
****************

****************
****** FIGURE 4 
****************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

keep if (year<2019 | (year==2019 & month<=7))
keep if retailer==0 
gen large = (IIROC_QUANTITY>25)
gen freq =1 

gen IIROC_QUANTITY_s = IIROC_QUANTITY if large==0
gen freq_s = freq if large==0

collapse (sum) IIROC_QUANTITY freq IIROC_QUANTITY_s freq_s, by(date trading_venue)
bys date: egen vol = total(IIROC_QUANTITY)
bys date: egen Freq = total(freq)
bys date: egen vol_s = total(IIROC_QUANTITY_s)
bys date: egen Freq_s = total(freq_s)

gen shareq_plat = IIROC_QUANTITY/vol*100 if trading_venue=="CanDeal"
gen share_plat = freq/Freq*100 if trading_venue=="CanDeal"
gen shareq_plat_s = IIROC_QUANTITY_s/vol_s*100 if trading_venue=="CanDeal"
gen share_plat_s = freq_s/Freq_s*100 if trading_venue=="CanDeal"

binscatter  share_plat share_plat_s shareq_plat shareq_plat_s date	if trading_venue=="CanDeal", linetype(none) yscale(r(0,50))  msymbol(circle_hollow diamond_hollow triangle_hollow square_hollow) mcolor(black%70 black%70 black%70 black%70) tlabel(20457 "2016"  20822 "2017" 21186 "2018" 21551 "2019" , labsize(large)) xti("") ylabel(, labsize(large)) yti(%, size(vlarge)) leg(order(1 2 3 4) row(1) label(1 "trades") label(2 "small trades") label(3 "volume")  label(4 "small volume")  region(lc(white)) size(large))
graph export "`dropbox_fig'/graph_candeal_share_2.png", replace	


****************
*** FIGURE 5 is created in Mainfile_ModelEstimation_STATA.do. 
*** FIGURES 6-9 are created in Matlab
****************

************************************************************
*** TABLES using data s.t. restrictions used in structural estimation 
************************************************************

****************
*** TABLE 1
****************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

keep if bidderid==18 | bidderid==24 | bidderid==46 | bidderid==61 | bidderid==67|bidderid==77 | bidderid==83 | bidderid==88 | bidderid==93 | bidderid==94 | bidderid==18001 | bidderid==24001 |bidderid==46001

*Homedealer for this sample of trades
do "Homedealer.do"
gen side=(IIROC_SIDE=="BUY")

*Define markup as for the figure in the draft
drop markup markup2 
gen markup   		=  (IIROC_YIELD - midyield_bl)
gen markup2 		=   markup if IIROC_SIDE=="BUY" 
replace markup2 	= - markup if IIROC_SIDE=="SELL" 

eststo: reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="CanDeal", absorb(LEI) vce(cluster LEI)
eststo: reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="CanDeal", absorb(exec_time_grid isin  ) 
eststo: reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="CanDeal", absorb(exec_time_grid isin  LEI) vce(cluster LEI)
eststo:  reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="OTC", absorb(LEI) vce(cluster LEI)
eststo:  reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="OTC", absorb(exec_time_grid isin ) 
eststo:  reghdfe markup2 homedealer   if trackclient=="market-wide"  &  trading_venue=="OTC", absorb(exec_time_grid isin  LEI bidderid)  vce(cluster LEI)
esttab using  "`dropbox_tab'/reg_markup_homedealer_both1.tex",  title("")  se ar2 nobaselevels label  mtitle("Platform" "OTC")   nonumbers   replace 
eststo clear

****************
*** TABLE 2 
****************

use "`local_data'/data_base_bonds_bills.dta", clear 
	*Note: Here I use the full sample to gain additional traders to create monthly market shares
	*However, the nubmers are similar when using the restricted sample

gen benchmark=0
replace benchmark=1 if benchmarkIsin==""
replace benchmark=0 if type=="bill" 

*choose period
gen month=month(date)
gen week=week(date)
egen period = group(year month )	

*aucitonday dummy 
bys period isin: egen auctionday = max(AuctionDate)
format auctionday %td

*auction dummy
gen auction = (auctionday!=.)
gen platform = (trading_venue=="CanDeal")

*drop stuff
drop if gleif_related=="Y"
keep  if market_type=="secondary"
keep if trading_venue=="CanDeal" | trading_venue=="OTC"
keep if trackclient=="market-wide"

*Create N_dealers variables
bys LEI bidderid trading_venue  period: gen a0=_n 
bys LEI  trading_venue  period a0: gen a1 = _N if a0==1
bys LEI trading_venue  period: egen N_dealers=max(a1)
	
bys LEI trading_venue  period: gen a2=N_dealers if trading_venue=="OTC"	
bys LEI period : egen N_dealers_otc=max(a2)
drop  a2
bys LEI trading_venue  period: gen a2=N_dealers if trading_venue=="CanDeal"	
bys LEI  period : egen N_dealers_can=max(a2)
drop  a2 a0 a1
	
bys LEI bidderid   period: gen a0=_n 
bys LEI   period a0: gen a1 = _N if a0==1
bys LEI  period: egen N_dealers_both=max(a1)
drop a1

keep if trackclient=="market-wide"

gen freq=1
collapse (sum) platform freq (max) benchmark (mean) N_dealers_both, by( period year  month isin LEI)

gen platform_share = platform/freq*100
label var benchmark "benchmark" 

tabstat freq 
tabstat N_dealers_both 

*IV regression 
eststo: reghdfe platform_share  benchmark, absorb( LEI year#month) vce(cluster LEI)
predict zfs, xb
label var zfs "platform_share"
eststo: reghdfe N_dealers_both  zfs  , absorb(  LEI year#month)  vce(cluster LEI)
esttab using  "`dropbox_tab'/N_dealers_IV_reg.tex",  title("IV regression")  se ar2 nobaselevels wide label mtitle("OLS" "IV1" "IV2")  nonumbers   replace 
eststo clear


****************
*** TABLE 3, 4
****************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

*id for each investor
drop lei
egen lei= group(LEI)
egen lei_max = max(lei)
bys LEI: gen ids = _n if LEI=="anonymous"	
replace lei = lei_max+ids  if LEI=="anonymous"	

*create quantity variables
replace IIROC_QUANTITY=IIROC_QUANTITY 
gen quant1 = IIROC_QUANTITY
gen quant2 = IIROC_QUANTITY*IIROC_QUANTITY
gen quant3 = IIROC_QUANTITY*IIROC_QUANTITY*IIROC_QUANTITY
gen side   = (IIROC_SIDE=="SELL")
gen candeal=(trading_venue=="CanDeal")
bys LEI IIROC_SIDE: egen med_quant = median(IIROC_QUANTITY)
gen quant_share_buy = (IIROC_QUANTITY - med_quant)* (IIROC_SIDE=="BUY")
gen quant_share_sell = (IIROC_QUANTITY - med_quant)* (IIROC_SIDE=="SELL")

*classify trades
gen tradesize1 = 0
replace tradesize1 = IIROC_QUANTITY if IIROC_QUANTITY<0.1
gen tradesize2 = 0
replace tradesize2 = IIROC_QUANTITY if IIROC_QUANTITY>=0.1 & IIROC_QUANTITY<1
gen tradesize3 = 0
replace tradesize3 = IIROC_QUANTITY if IIROC_QUANTITY>=1 & IIROC_QUANTITY<5
gen tradesize4 = 0
replace tradesize4 = IIROC_QUANTITY if IIROC_QUANTITY>=5 & IIROC_QUANTITY<25
gen tradesize5 = 0
replace tradesize5 = IIROC_QUANTITY if IIROC_QUANTITY>=25

*benchmark
gen benchmark=0
replace benchmark=1 if benchmarkIsin==""
replace benchmark=0 if type=="bill" 

*label 
gen retailer_intro=(retailer==1)
label define retailer_intro_lab 0 "institutional (w/ access)" 1 "retail  (w/o  access)"				   
label values retailer_intro retailer_intro_lab  

gen tradingvenue_intro=(trading_venue=="CanDeal")
label define tradingvenue_intro_lab 0 "bilateral" 1 "platform"				   
label values tradingvenue_intro tradingvenue_intro_lab  

***TABLE 3 
drop markup2 markup 
gen markup = IIROC_YIELD - midyield_bl
gen markup2 = markup if IIROC_SIDE=="BUY"
replace markup2 = markup if IIROC_SIDE=="SELL"
gen platform 	= (trading_venue=="CanDeal") 
eststo: reg markup2  platform 
eststo: reghdfe markup2  platform , absorb(LEI)   vce(cluster  LEI )
eststo: reghdfe markup2  platform , absorb(bidderid isin_id exec_time_grid LEI)   vce(cluster  LEI )
eststo: reghdfe markup2  platform IIROC_QUANTITY, absorb(bidderid isin_id exec_time_grid LEI)   vce(cluster  LEI ) // this is in the table
esttab using  "`dropbox_tab'/reg_markup_candeal_otc2.tex",   se ar2 wide nobaselevels label mtitle("(OLS)" "(FE)" "(FE)" )  title("platform prices") nonumbers   replace 
eststo clear

***TABLE 4 
label var side "investor sells"
eststo: reghdfe candeal  tradesize* benchmark  if  retailer==0  , absorb(lei ) vce(cluster lei)
esttab using  "`dropbox_tab'/reg_candeal_quantitygrid.tex", wide title("") se ar2 nobaselevels label mtitle("")  nonumbers   replace 
eststo clear


************************************************************
*** APPENDIX FIGURES 
************************************************************

********************************
*** APPENDIX FIGURE A2 
********************************

sort tradingvenue_intro
by tradingvenue_intro: egen pQ1 = pctile(IIROC_QUANTITY), p(5)
by tradingvenue_intro: egen pQ99 = pctile(IIROC_QUANTITY), p(95)

graph box IIROC_QUANTITY if IIROC_QUANTITY>=pQ1 & IIROC_QUANTITY<=pQ99, over(tradingvenue_intro,label(labsize(vlarge)))  ylabel(,labsize(vlarge))	yti("mio CAD", size(vlarge))   graphregion(color(white)) marker(1, msize(tiny))  yti("million C$", size(vlarge))   marker(1, msize(vsmall) msymbol(circle_hollow) mcolor(black%70)) graphregion(color(white)) bar(1, fcolor(white) lcolor(black)) 
graph export "`dropbox_fig'/graph_candeal_quantity_full_sample.png", replace	


********************************
**** APPENDIX FIGURE A1 
********************************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

keep if c_type!=""
keep if retailer==0

collapse (sum) IIROC_QUANTITY, by(trading_venue c_type)
replace IIROC_QUANTITY=IIROC_QUANTITY/10^6 // in tr 

bys trading_venue: egen tot_vol = total(IIROC_QUANTITY)

gen nums =1 		if c_type=="asset manager"
replace nums =2 	if c_type=="pension"  
replace nums =3 	if c_type=="bank" 
replace nums =4 	if c_type=="other irroc member" 
replace nums =5 	if c_type=="public entity" 
replace nums =6 	if c_type=="insurance" 
replace nums =7 	if c_type=="other broker" 
replace nums =8 	if c_type=="non-financial company" 

replace c_type="insurance company" 	if c_type=="insurance"
replace c_type="pension fund" 		if c_type=="pension"
replace c_type="irroc member" 		if c_type=="other irroc member"
replace c_type="brokerage service" 	if c_type=="other broker"

gen quant1 = IIROC_QUANTITY/tot_vol*100 if trading_venue=="OTC"
gen quant2 = IIROC_QUANTITY/tot_vol*100 if trading_venue=="CanDeal"

graph hbar quant1 quant2, over(c_type,  sort(nums) lab(labsize(medlarge))) yti("", size(medlarge))  leg(order(1 2) label(1 "bilateral") label(2 "platform") region(lc(white))) bar(1, fcolor(navy%70) lcolor(black)) bar(2, fcolor(emidblue%40) lcolor(black))   graphregion(color(white))  legend(size(medlarge)) 
graph export "`dropbox_fig'/graph_clients_platform_OTC.png", replace	


********************************
*** APPENDIX FIGURE A3 
********************************

use "`local_data'/data_base_bonds_bills.dta", clear 
keep if market_type=="secondary"
drop if  gleif_related=="Y"
drop if Dleg ==1 // avoid double counting for the dealer

replace quantity=IIROC_QUANTITY

foreach i in  1  {
preserve 

if (`i'==2){
	replace isin_id=0
}

collapse (sum) quantity IIROC_QUANTITY, by(counter_type date isin_id )

gen volC = quantity if counter_type=="CLIENT"
gen volD = quantity if counter_type=="DEALER"
gen volB = quantity if counter_type=="BROKER"

gen volC2 = IIROC_QUANTITY if counter_type=="CLIENT"
gen volD2 = IIROC_QUANTITY if counter_type=="DEALER"
gen volB2 = IIROC_QUANTITY if counter_type=="BROKER"

collapse volC volD volB volC2 volD2 volB2, by(date isin_id)
replace volC = 0 if volC==.
replace volD = 0 if volD==.
replace volB = 0 if volB==.
replace volC2 = 0 if volC2==.
replace volD2 = 0 if volD2==.
replace volB2 = 0 if volB2==.

tabstat volC volD volB, stats(mean p50 min max)
tabstat volC2 volD2 volB2, stats(mean p50 min max)

gen vol = volC 

egen p90C = pctile(volC2), p(95)
egen p90D = pctile(volD2), p(95)

graph box volC2 volD2 if volC2<=p90C & volD2<=p90D, yti("million C$", size(vlarge)) ylabel(,labsize(vlarge))  leg(order(1 2) row(1)  label(1 "dealer-investor") label(2 "dealer-dealer") region(lc(white))) graphregion(color(white))  marker(1, msize(vsmall) msymbol(circle_hollow) mcolor(black%70))  bar(1, fcolor(white) lcolor(black))  marker(2, msize(vsmall) msymbol(circle_hollow) mcolor(gray%70))  bar(2, fcolor(white) lcolor(gray))   legend(size(vlarge)) 
graph export "`dropbox_fig'/graph_trade_vol_segment_`i'.png", replace	
restore 
}


********************************
*** APPENDIX FIGURE A4 
********************************

use "`local_data'/data_base_bills_clients_matlab_2022b.dta", clear
drop if gleif_related=="Y"

*Create  id for each investor
drop lei
egen lei= group(LEI)
egen lei_max = max(lei)
bys LEI: gen ids = _n if LEI=="anonymous"	
replace lei = lei_max+ids  if LEI=="anonymous"	

preserve 
bys lei year week: gen N_trades_t = _N 
bys lei year week: gen n_trades_t = _n 

collapse N_trades_t, by(lei year week)

hist N_trades_t , percent lcolor(gs12) fcolor(gs12) bin(50) xtitle("number of times an investor trades in a week", size(vlarge)) ytitle("%", size(vlarge))  graphregion(color(white))  ylabel(,labsize(vlarge)) xlabel(,labsize(vlarge))
graph export "`dropbox_fig'/hist_N_trades_per_week.png", replace

tabstat N_trades_t, stats(count p50 mean min max)
tab N_trades 
restore 


********************************
*** APPENDIX FIGURE A5 is created in EventStudy.do 
*** APPENDIX FIGURE A6 is craeted in Matlab
********************************

************************************************************
*** APPENDIX TABLES 
************************************************************

********************************
*** APPENDIX TABLE A1 is created in BaseData.do
********************************

********************************
*** APPENDIX TABLE A2 
********************************

use "`local_data'/data_base_bonds_bills.dta", clear 
keep if market_type=="secondary"
drop if  gleif_related=="Y"

*keep dealers and investors and tread brokers as dealers
replace counter_type="DEALER" if counter_type=="BROKER"
keep if counter_type=="DEALER" | counter_type=="CLIENT"

bys bidderid date isin counter_type: egen Qi = total(quantity)

replace Qi = -Qi
gen netsupply = Qi if Qi>0
gen netdemand = Qi if Qi<0
gen breakeven = Qi if Qi==0

collapse Qi netsupply netdemand breakeven, by(bidderid date isin counter_type)

gen netsupplyC = netsupply if counter_type=="CLIENT"
gen netsupplyD = netsupply if counter_type=="DEALER"
gen netdemandC = netdemand if counter_type=="CLIENT" 
gen netdemandD = netdemand if counter_type=="DEALER" 

gen QiC = Qi  if counter_type=="CLIENT"
gen QiD = Qi  if counter_type=="DEALER"

collapse netsupplyC netsupplyD netdemandC netdemandD QiC QiD, by(bidderid date isin)
egen isin_id = group(isin)

eststo: reg QiD	 QiC
eststo: reghdfe QiD QiC , absorb( bidderid)   vce(cluster bidderid ) 
eststo: reghdfe QiD QiC , absorb(date bidderid)   vce(cluster bidderid ) 
eststo: reghdfe QiD QiC , absorb(date isin bidderid)   vce(cluster bidderid isin) 
esttab using  "`dropbox_tab'/reg_interdealermarket.tex",  title("") se ar2 nobaselevels label mtitle("")  nonumbers   replace 
eststo clear


********************************
*** APPENDIX TABLES A3 and A6 are created in MainFile_ModelEstimation_STATA.do
*** APPENDIX TABLES A4 and A5 are created in Matlab
********************************



	
